<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use app\middleware\AuthAdmin;

class Activity{
    protected $middleware = [AuthAdmin::class];
    const storageStie = 'http://1.12.76.149:15002';
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function list(){
        if(Request::isPost()){
            $keyword=input('param.keyword');
            $page=input('param.page',1);
            $page_size=input('param.page_size',25);
            $where=[];

            if($keyword){
                $where[]=['title','like',"%$keyword%"];
            }
            $data=Db::table('activity')->field("id,title,fee,is_publish,profile,is_booking,FROM_UNIXTIME(start_time,'%Y-%m-%d') as start_time,FROM_UNIXTIME(end_time,'%Y-%m-%d') as end_time")
            ->field("CONCAT('https://darong.storage.1415926.com.cn/tmp_wxacode/activity/',id,'.png') as wxacode")
            ->where($where)
            ->paginate([
                    'list_rows' => $page_size,
                    'page'      => $page,
                ]);
    
            $total=$data->total();
            $data=$data->items();
            $result=['code'=>200,'message'=>'获取成功','success'=>true,'result'=>['list'=>$data,'total'=>$total]];
            return json($result);
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create(){
        if(Request::isPost()){
            try{
                $start_time=input('param.start_time',0);
                $end_time=input('param.end_time',0);
                $id=Db::table('activity')->insertGetId([
                    'title'=>input('param.title'),
                    'fee'=>input('param.fee',0),
                    'start_time'=>floor($start_time/1000),
                    'end_time'=>floor($end_time/1000),
                    'profile'=>input('param.profile','')
                ]);
                $cover=input('param.cover',[]);
                if(count($cover)>0){//记录封面图
                    $cover=moveImage($cover,'activity',$id);
                }
                Db::table('activity')->where(['id'=>$id])->update([
                        'cover'=>json_encode($cover)
                ]);
                $access_token=getAccessToken();
                $scene = 'activityId='.$id; // 场景值，可根据业务需要传递参数:cite[4]
                $page = 'pages/activity/detail'; // 扫描小程序码后进入的页面:cite[4]
                $savePath='/www/wwwroot/storage.darong1994.cn/tmp_wxacode/activity/'.$id.'.png';
                $kk=setWxacode($access_token,$scene, $page, $savePath, 430);
                return json(['code'=>200,'message'=>'添加成功','success'=>true,'cover'=>['data'=>$cover,'total'=>count($cover)]]);
            }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
            //录入部分信息
           
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     */
    public function detail(){
        if(Request::isPost()){
            $id=input('param.id');
            $detail=Db::table('activity')->field('*,FROM_UNIXTIME(start_time) as start_time,FROM_UNIXTIME(end_time) as end_time')->where(['id'=>$id])->find();
            $detail['cover']=$detail['cover']?json_decode($detail['cover'],true):[];
            // $datail['activity_time']=[$detail['start_time']*1000,$detail['end_time']*1000];
            $detail['tmp_cover']=[];
            foreach($detail['cover'] as $key=>$value){
                
                $detail['tmp_cover'][]=['name'=>time().$key,'url'=>'https://darong.storage.1415926.com.cn/'.$value];
            }
            $result=['code'=>200,'message'=>'获取成功','success'=>true,'result'=>$detail];
            return json($result);
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(){
        if(Request::isPost()){
            try{
                $id=input('param.id');
                $cover=input('param.cover',[]);
                // $activity_time=input('param.activity_time',[]);
                if(count($cover)>0){
                    $cover=moveImage($cover,'activity',$id);
                }
                $start_time=input('param.start_time',0);
                $end_time=input('param.end_time',0);
                $detail=Db::table('activity')->where(['id'=>$id])->update([
                    'title'=>input('param.title'),
                    'cover'=>json_encode($cover),
                    'fee'=>input('param.fee',0),
                    'start_time'=>floor($start_time/1000),
                    'end_time'=>floor($end_time/1000),
                    'profile'=>input('param.profile','')
                ]);
                return json(['code'=>200,'message'=>'编辑成功','success'=>true]);

            }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

     /**
     * 上传图片
     */
    public function uploadImage(){
        if(Request::isPost()){
            $file = request()->file();
            try{
                
                validate(['image'=>'fileSize:2097152|fileExt:jpg,png,jpeg'])->check($file);
                $image = request()->file('image');
                $savename =\think\facade\Filesystem::disk('toStorageUrl')->putFile( '/tmp/activity', $image);
                // $site='http://1.12.76.149:15002';
                $site=self::storageStie;
                $url=$site.'/'.$savename;
                return json(['code'=>200,'success'=>true,'message'=>'上传成功','result'=>['site'=>$site,'savename'=>$savename,'url'=>$url]]);
            } catch (\think\exception\ValidateException $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e->getMessage()]);
            }
        }
    }
     /**
     * 更改活动状态
     */
    public function changeActiviyStatus(){
        if(Request::isPost()){
            try{
                $param=input('param.');
                if(!(isset($param['activityId'])||isset($param['field'])||isset($param['value']))){
                    return json(['code'=>200,'success'=>false,'message'=>'参数错误']);
                }
                $detail=Db::table('activity')->where(['id'=>$param['activityId']])->update([
                    $param['field']=>$param['value']
                ]);
                return json(['code'=>200,'message'=>'设置成功','success'=>true,'param'=>input('param.')]);
            }catch (Exception $e) {
                return json(['code'=>200,'success'=>false,'message'=>$e]);
            }
        }
    }
}
